/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 * 
 *
 *
 */
package rad.framework.jmx;

import java.util.Date;
import java.util.List;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.timer.Timer;

import rad.framework.lang.DateUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.mx.util.MBeanProxy;
import org.jboss.mx.util.MBeanProxyCreationException;

/**
 * This is a utility class that provides convenience methods for JMX api. Feel
 * free to use these or not.
 * 
 * @author
 * @version 1.0
 * 
 */
public class JMXUtil {

	private static final Log log = LogFactory.getLog(JMXUtil.class);

	public static Object getMBean(Class<?> clazz, String name) {
		return getMBean(clazz, createObjectName(name));
	}
	
	public static Object getMBean(Class<?> clazz, ObjectName name) {
		Object mbean;
		try {
			MBeanServer server = locateMBeanServer(null);
			// MBeanServerLocator.locateJBoss();
			mbean = MBeanProxy.get(clazz, name, server);
			if (mbean == null)
				throw new RuntimeException("Cannot obtain mbean: " + name);

			return mbean;
		} catch (MBeanProxyCreationException ex) {
			throw new RuntimeException("Cannot obtain proxy to mbean: " + name, ex);
		}
	}

	/**
	 * @param name
	 * @return
	 */
	public static ObjectName createObjectName(String name) {
		try {
			return new ObjectName(name);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @param agentId
	 * @return
	 */
	static public MBeanServer locateMBeanServer(String agentId) {
		List servers = MBeanServerFactory.findMBeanServer(agentId);
		// Check to see if an MBeanServer is registered.
		if (servers == null || servers.size() == 0) {
			throw new RuntimeException(
					"Unable to locate an MBeanServer instance"
							+ (agentId != null ? " with agent id [" + agentId
									+ "]" : ""));
		}
		if (servers.size() > 1) {
			log.warn("Found more than one MBeanServer instance"
					+ (agentId != null ? " with agent id [" + agentId + "]"
							: "") + ". Returning first from list.");
		}
		MBeanServer server = (MBeanServer) servers.get(0);
		if (log.isDebugEnabled()) {
			log.debug("Found MBeanServer: " + server);
		}
		return server;
	}

	/**
	 * Create the listener
	 * 
	 * @param timer
	 * @param listener
	 * @param period
	 * @param occurrences
	 * @param name
	 * @param description
	 * @return
	 */
	static public Integer init(Timer timer, NotificationListener listener,
			Date startTime, Long period, Long occurrences, String name,
			String description) {
		Integer notificationId = null;
		// Registering the listener
		timer.addNotificationListener(listener, null, listener.getClass());
		// Adding the notification to the Timer and assigning the
		// ID that the Timer returns to a variable
		if (startTime == null) {
			startTime = DateUtil.addMinutes(5);
		}
		if (occurrences == null) {
			notificationId = timer.addNotification(name, description, listener,
					startTime, period);
		} else {
			notificationId = timer.addNotification(name, description, listener,
					startTime, period, occurrences);
		}
		timer.start();
		return notificationId;
	}

	/**
	 * Close the listener
	 * 
	 * @param timer
	 * @param notificationId
	 * @throws Exception
	 */
	static public void destroy(Timer timer, Integer notificationId)
			throws Exception {
		timer.stop();
		timer.removeNotification(notificationId);
	}

	/**
	 * @param notif
	 * @return
	 */
	static public String print(Notification notif) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("\ntoString:   " + notif.toString());
		buffer.append("\nmessage:    " + notif.getMessage());
		buffer.append("\nseq Number: " + notif.getSequenceNumber());
		buffer.append("\nsource:     " + notif.getSource());
		buffer.append("\ntime:       " + notif.getTimeStamp());
		buffer.append("\ntype:       " + notif.getType());
		buffer.append("\ndata:       " + notif.getUserData());
		return buffer.toString();
	}
}
